//
//  ViewController.m
//  BowTie
//
//  Created by Mac on 15/11/14.
//  Copyright © 2015年 riverlj. All rights reserved.
//

#import "ViewController.h"
#import "Bowtie.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UISegmentedControl *segementedControl;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *ratingLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeWornLabel;
@property (weak, nonatomic) IBOutlet UILabel *lastWornLabel;
@property (weak, nonatomic) IBOutlet UILabel *favoriteLabel;

@property (nonatomic, strong)Bowtie *currentBowtie;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self insertSamepleData];
    
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Bowtie"];
    NSString *firstTitle = [self.segementedControl titleForSegmentAtIndex:0];
    request.predicate = [NSPredicate predicateWithFormat:@"searchKey == %@", firstTitle];
    NSError *error = nil;
    NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"获取数据失败，错误信息为:error=%@",error);
    }
    [self pupulate:result.firstObject];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)wear:(id)sender {

    NSInteger times = [self.currentBowtie.timesWorn integerValue];
    self.currentBowtie.timesWorn = [NSNumber numberWithInteger:times + 1];
    self.currentBowtie.lastWorn = [[NSDate alloc]init];
    NSError *error = nil;
    [self.managedObjectContext save:&error];
    if (error) {
        NSLog(@"保存数据失败，失败信息为：error=%@",error);
    }
    
    [self pupulate:self.currentBowtie];
    
    

}
- (IBAction)rate:(id)sender {
    UIAlertController *alertCtl = [UIAlertController alertControllerWithTitle:@"New Rating" message:@"Rate this bow tie" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alertCtl.textFields[0];
        [self updateRating:textField.text];
    }];
    
    [alertCtl addAction:cancelAction];
    [alertCtl addAction:saveAction];
    [alertCtl addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    [self presentViewController:alertCtl animated:NO completion:nil];
}

- (void)insertSamepleData{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Bowtie"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"searchKey != nil"];
    
    NSError *error = nil;
    NSInteger count = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
    if (error) {
        NSLog(@"获取数据失败，错误信息为：error=%@",error);
    }
    if (count > 0) {
        return;
    }
    NSString *path = [[NSBundle mainBundle] pathForResource:@"SampleData" ofType:@"plist"];
    NSArray *dataArray = [NSArray arrayWithContentsOfFile:path];
    for (NSDictionary *dic in dataArray) {
        //插入数据
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Bowtie" inManagedObjectContext:self.managedObjectContext];
        Bowtie *bowtie = [[Bowtie alloc]initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
        bowtie.name = dic[@"name"];
        bowtie.searchKey = dic[@"searchKey"];
        bowtie.rating = dic[@"rating"];
        NSDictionary *colorDic = dic[@"tintColor"];
        bowtie.tintColor = [self colorFromDic:colorDic];
        NSString *imageName = dic[@"imageName"];
        UIImage *image = [UIImage imageNamed:imageName];
        bowtie.photoData = UIImagePNGRepresentation(image);
        bowtie.lastWorn = dic[@"lastWorn"];
        bowtie.timesWorn = dic[@"timesWorn"];
        bowtie.isFavorite = dic[@"isFavorite"];
        NSError *error = nil;
        //如果是想做更新操作：只要在更改了实体对象的属性后调用[context save:&error]，就能将更改的数据同步到数据库
        [self.managedObjectContext save:&error];
        if (error) {
            NSLog(@"保存数据失败,错误信息为error=%@",error);
        }
    }

 
}

-(UIColor *)colorFromDic:(NSDictionary *)dic {
    NSNumber *red = dic[@"red"];
    NSNumber *green = dic[@"green"];
    NSNumber *blue = dic[@"blue"];
    
    UIColor *color = [UIColor colorWithRed:red.floatValue/255.0 green:green.floatValue/255.0 blue:blue.floatValue/255.0 alpha:1.0];
    
    return color;
}

- (void)pupulate:(Bowtie *)bowtie {
    self.imageView.image = [UIImage imageWithData:bowtie.photoData];
    self.nameLabel.text = bowtie.name;
    self.ratingLabel.text = [NSString stringWithFormat:@"Rating:%2.f",bowtie.rating.doubleValue];
    self.timeWornLabel.text = [NSString stringWithFormat:@"times worn:%ld", bowtie.timesWorn.integerValue];
    self.lastWornLabel.text = [NSString stringWithFormat:@"Last worn: %@", bowtie.lastWorn];
    self.favoriteLabel.hidden = bowtie.isFavorite.boolValue;
    self.view.tintColor = bowtie.tintColor;
}

- (void)updateRating:(NSString *)numericString{
    self.currentBowtie.rating = [NSNumber numberWithDouble:numericString.doubleValue];
    NSError *error = nil;
    [self.managedObjectContext save:&error];
    if (error.domain == NSCocoaErrorDomain && (error.code == NSValidationNumberTooLargeError|| error.code == NSValidationNumberTooSmallError )) {
        [self rate:self.currentBowtie];
    }
    [self pupulate:self.currentBowtie];
    
}
- (IBAction)segementChanged:(UISegmentedControl *)sender {
    NSString *selectedVale = [sender titleForSegmentAtIndex:sender.selectedSegmentIndex];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Bowtie"];
    request.predicate = [NSPredicate predicateWithFormat:@"searchKey=%@",selectedVale];
    NSError *error = nil;
    NSArray *result = [self.managedObjectContext executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"获取数据失败，错误信息为：error=%@",error);
    }
    self.currentBowtie = result.firstObject;
    
    [self pupulate:self.currentBowtie];
    NSLog(@"%@",self.currentBowtie.name);
}

@end
